import axios from 'axios'
import qs from 'qs'

const request_type_form = 'application/x-www-form-urlencoded; charset=UTF-8';
const request_type_json = 'application/json; charset=UTF-8';
const request_type_data = 'multipart/form-data; charset=UTF-8'

let baseURL = process.env.VUE_APP_BASE_URL;
axios.defaults.timeout = 5000;

// 请求数据拦截处理
axios.interceptors.request.use(config => {
// code... 你的逻辑
  if (config.url.includes("http") || config.url.includes("https")) {

  }else {
    config.url = baseURL + config.url
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 返回数据拦截处理
axios.interceptors.response.use(response => {
  //code... 你的逻辑
  return response.data //直接返回后台返回的json object
}, error => Promise.reject(error.response))

const _request = (method, url, data) => {
  const headers = {}
  const configData = {
    url, // 请求的地址
    headers
  }

  if (method === 'get') {
    configData.method = 'get';
    configData.params = data// get 请求的数据
  } else if (method === 'postForm') {
    configData.method = 'post';
    if (data instanceof FormData) {
      configData.headers['Content-Type'] = request_type_data;
      configData.data = data
    } else {
      configData.headers['Content-Type'] = request_type_form;
      configData.data = qs.stringify(data)
    }
  } else if (method === 'postJson') {
    configData.method = 'post';
    configData.headers['Content-Type'] = request_type_json;
    configData.data = data
  } else if (method === 'put') {
    configData.method = 'put';
    configData.params = data
  } else if (method === 'delete') {
    configData.method = 'delete';
    configData.params = data
  }
  return axios(configData)
}


class AxiosUtil {
  get = (url, data = {}) => {
    return _request('get', url, data)
  };

  postForm = (url, data = {}) => {
    return _request('postForm', url, data)
  };

  postJson = (url, data = {}) => {
    return _request('postJson', url, data)
  };

  put = (url, data = {}) => {
    return _request('put', url, data)
  };

  delete = (url, data = {}) => {
    return _request('delete', url, data)
  };

  post = this.postJson // 默认post的Content-Type是application/json

}

export default new AxiosUtil();
